rm(list = ls())

## 

library(tidyverse)
library(rdrobust)
library(broom)
source('code/function_tidy_rd.R')

## Get MIP data

civ_mip <- read_rds("data/civey_issue_replication.rds") %>% 
  dplyr::select(id, date, climate) %>% 
  filter(!dplyr::between(date, as.Date("2021-07-12"), 
                         as.Date('2021-07-19'))) %>% 
  mutate(period = as.numeric(as.factor(date))) %>% 
  mutate(period = period - 
           unique(period[which(date == as.Date("2021-07-20"))])) %>% 
  filter(abs(period) < 121)

## Declare variables

y <- civ_mip$climate
x <- civ_mip$period

## Estimate RD

r <- rdrobust::rdrobust(y =y * 100, x = x)
summary(r)

#### Figure A.10 a -- most important issue ####

p <- rdrobust::rdplot(y = y * 100, 
                      x = x, 
                      h = r$bws[1,1],
                      x.lim = c(-35, 35),
                      col.dots = 'grey60',
                      col.lines = 'black',
                      p = 1)

## Some modifications

p$rdplot + 
  theme_bw() + 
  xlim(c(-20, 20)) + 
  xlab("Days rel. to flood") + 
  ylab("Climate change salience (%)") + 
  theme(plot.title = element_blank()) + 
  scale_x_continuous(breaks = seq(-30, 30, 10))

## Green party support
## Get data 

civ <- read_rds("data/civey_party_replication.rds") %>% 
  dplyr::select(id, date, green) %>% 
  filter(!dplyr::between(date, as.Date("2021-07-12"), 
                         as.Date('2021-07-19'))) %>% 
  mutate(period = as.numeric(as.factor(date))) %>% 
  mutate(period = period - unique(period[which(date == 
                                                 as.Date("2021-07-20"))])) %>% 
  filter(abs(period) < 121)

## Declare variables

y_green <- civ$green
x_green <- civ$period

## Estimate RD

r_green <- rdrobust::rdrobust(y = y_green * 100, x = x_green)
r_green %>% tidy_rd(se_nr = 3)

#### Figure A.10 b -- green party support ####

p_green <- rdrobust::rdplot(y = y_green * 100, 
                            x = x_green, 
                            h = r_green$bws[1,1],
                            x.lim = c(-35, 35),
                            col.dots = 'grey60',
                            col.lines = 'black',
                            p = 1)

## Modifications

p_green$rdplot + 
  theme_bw() + 
  xlim(c(-35, 35)) + 
  xlab("Days rel. to flood") + 
  ylab("Green party support (%)") + 
  theme(plot.title = element_blank()) + 
  scale_x_continuous(breaks = seq(-30, 30, 10))

#### Table A.4 - RD results ####

t_df <- r %>% tidy_rd(3) %>% 
  bind_rows(r_green %>% tidy_rd(3)) %>% 
  dplyr::select(estimate, conf.high, conf.low, n, bw_left_h) %>% 
  mutate_all(list(~round(., 3))) %>% 
  mutate(ci = paste0('[', conf.low, ', ', conf.high, ']')) %>%
  dplyr::select(estimate, ci, n, bw_left_h) %>% 
  mutate_all(as.character) %>% t()

t_df
